package com.javaee.ch13.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaee.ch13.common.exceptions.ServiceException;
import com.javaee.ch13.entity.Reader;
import com.javaee.ch13.mapper.ReaderMapper;
import com.javaee.ch13.service.ReaderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javaee.ch13.web.dto.queryDto.ReaderQueryDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import com.javaee.ch13.web.dto.ReaderDto;

import java.util.List;

/**
 * <p>
 * 读者表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-05
 */
@Slf4j
@Service
@Transactional
public class ReaderServiceImpl extends ServiceImpl<ReaderMapper, Reader> implements ReaderService {

    @Autowired
    private ReaderMapper readerMapper;

    /**
    * 添加
    */
    @Override
    public void addReader(ReaderDto addDto) {
        Reader reader = new Reader();
        // 业务逻辑

        // 将dto数据复制到${$objName}实体类}
        BeanUtils.copyProperties(addDto, reader);
        // 设置默认字段

        // 保存对象
        if(!super.save(reader)) {
            throw  new ServiceException("系统错误,添加操作失败!")   ;
        }
    }


    /**
    * 复杂条件查询
    */
    @Override
    public List<Reader> query(ReaderQueryDto queryDto) {
          // 查询
        List<Reader> list =this.lambdaQuery()
                            .list();
         return list;
    }

    /**
     * 更新
     */
    @Override
    public void updateReader(ReaderDto updateDto) {
             Reader reader = new Reader();

         // 将dto转换为实体类
         BeanUtils.copyProperties(updateDto, reader);

         // 进行增量更新
        if(!this.updateById(reader)){
            throw new ServiceException("系统错误,更新操作失败!");
        }
    }

    /**
     * 分页查询
     */
    @Override
    public Page<Reader> getReaderPage(int pageNum, int pageSize, String name, String email, Integer status) {
        return this.lambdaQuery()
                .like(name != null && !name.isEmpty(), Reader::getName, name)
                .like(email != null && !email.isEmpty(), Reader::getEmail, email)
                .eq(status != null, Reader::getStatus, status)
                .select(Reader::getName, Reader::getStatus, Reader::getEmail)
                .page(new Page<>(pageNum, pageSize));
    }

}
